package lib.gui;
import java.util.Enumeration;

import javax.microedition.io.file.FileSystemRegistry;

import lib.UrlFactory;
import lib.classes.Profile;
import model.DB;
import net.rim.blackberry.api.bbm.platform.BBMPlatformContext;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.FontManager;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;

import com.blackberry.toolkit.ui.component.banner.Banner;
public class ScreenTemplate extends MainScreen
{
	public static boolean WIFI_ONLY = true;
	public static UrlFactory urlFactory;
	
	VerticalFieldManager _pane;
	final long _defaultStyle = VERTICAL_SCROLL;
	public static FontFamily burstMyBubbleFont;
	public static FontFamily valerieHandFont;
	public static FontFamily completeInHimFont;
	
	public static final Background background = BackgroundFactory.createBitmapBackground(Bitmap.getBitmapResource("img/dark-bg.png"), Background.POSITION_X_LEFT, Background.POSITION_Y_TOP, Background.REPEAT_BOTH );//BackgroundFactory.createSolidBackground(Color.LIGHTBLUE);
	public Banner banner ;
	private static int batteryVisibility = Banner.PROPERTY_VALUE_DEFAULT;
	public static boolean bannerHasTitle = false;
	public static BBMPlatformContext platformContext;
	public static Profile profile;
	public static DB _db;
	public HorizontalFieldManager appIconField ;
	public ScreenTemplate(String title, boolean showBanner)
	{
		super();
		initAppFonts();
		doBackground();
		setTitle(title, showBanner);
		//BBMInfo = (BBMInfo == null? new DefaultBBInfo(): BBMInfo);
	}
	
	public ScreenTemplate (String title, long style, boolean showBanner)
	{
		super( style );
		initAppFonts();
		doBackground();
		setTitle(title, showBanner);
	}
	
	public static void initDB()
	{
		if(_db == null)
		{
			_db = new DB();
		}
	}
	public void setTitle( String title, boolean showBanner )
    {
		if(showBanner)
		{
			banner = new Banner();
			banner.addTitle(title);
			bannerHasTitle = true;
			banner.setPropertyValue(Banner.PROPERTY_CELLULAR_VISIBILITY, Banner.PROPERTY_VALUE_ON);
			banner.setPropertyValue(Banner.PROPERTY_WIFI_VISIBILITY, Banner.PROPERTY_VALUE_ON);
			banner.addSignalIndicator();
			banner.setPropertyValue(Banner.PROPERTY_BATTERY_VISIBILITY, batteryVisibility);
			//banner.
			super.setBanner( banner );
		}
		appIconField = new HorizontalFieldManager(USE_ALL_WIDTH | FIELD_HCENTER);
		BitmapField appIcon = new BitmapField();
		appIconField.add(appIcon);
		super.setTitle(appIconField);
		/* LabelField logo_prefix = new LabelField("Mingle"){
        	public void paint( Graphics g )
        	{
        		g.setColor( Color.WHITE );
        		super.paint(g);
        	}
        };
        logo_prefix.setFont(completeInHimFont.getFont(Font.PLAIN, 22));
        LabelField logo_suffix = new LabelField(" YorkU"){
        	public void paint( Graphics g )
        	{
        		g.setColor( Color.DARKOLIVEGREEN );
        		super.paint(g);
        	}
        };
        logo_suffix.setFont(completeInHimFont.getFont(Font.PLAIN, 22));
        
        header = new TwoColumnFieldManager(Display.getWidth() / 2, Field.USE_ALL_WIDTH);
        HorizontalFieldManager _left = new HorizontalFieldManager( FIELD_LEFT);
        _left.add(logo_prefix);
        _left.add(logo_suffix);
        _left.setPadding(new XYEdges(4, 4, 4, 5));
        
       
        //header.add(_left);
        
        LabelField titleLabel = new LabelField( title );
        titleLabel.setFont(  completeInHimFont.getFont(Font.PLAIN, 22));
        HorizontalFieldManager _right = new HorizontalFieldManager( Field.FIELD_RIGHT);
        _right.add(titleLabel);
        _right.setPadding(new XYEdges(4, 5, 4, 4));
        //header.add(_right);
        
       TwoColumnField xy = new TwoColumnField(_left, _right, USE_ALL_WIDTH);
        header.add(xy);
        header.setBackground(BackgroundFactory.createSolidBackground(Color.SILVER));
        */
		//Banner banner = 
        //super.setBanner( banner );
        
        /*banner = new HorizontalFieldManager(USE_ALL_WIDTH)
        {
			public void paintBackground( Graphics g )
			{
				g.setBackgroundColor(Color.WHITE);
				g.clear();
			}
        };
        super.setTitle( banner );*/
    }
	
	public void doBackground()
	{
		VerticalFieldManager internalField = new VerticalFieldManager( _defaultStyle )
		{
			protected void sublayout( int width, int height ) {
				
				int dispHeight = Display.getHeight() - banner.getPreferredHeight() - appIconField.getPreferredHeight();
				super.sublayout(width, dispHeight);
				setExtent(width, dispHeight);
			}
			
		};
		_pane = new VerticalFieldManager( USE_ALL_WIDTH )
		{
			/*protected void sublayout( int width, int height ) {
				
				int dispHeight = Display.getHeight() - banner.getPreferredHeight() - appIconField.getPreferredHeight();
				int _h = height - banner.getPreferredHeight() - appIconField.getPreferredHeight();
				int _height = _h < dispHeight ? dispHeight: _h;
				super.sublayout(width, _height);
				setExtent(width, _height);
				
			}*/
		};
		internalField.setBackground(background);
		internalField.add(_pane);
		super.add( internalField );
		
	}
	
	/**
	 * Initialize the Fonts Needed for this application 
	 * (First thing to do at the start of the constructor)
	 */
	private void initAppFonts() 
	{
		try 
		{
			FontManager.getInstance().load("fonts/BurstMyBubble.ttf", "burstmybubble", FontManager.APPLICATION_FONT);
			FontManager.getInstance().load("fonts/Valerie Hand.ttf", "valeriehand", FontManager.APPLICATION_FONT);
			FontManager.getInstance().load("fonts/Complete in Him.ttf", "completeinhim", FontManager.APPLICATION_FONT);
			
			valerieHandFont = FontFamily.forName("valeriehand");
			burstMyBubbleFont = FontFamily.forName("burstmybubble");
			completeInHimFont = FontFamily.forName("completeinhim");
			
		} catch (ClassNotFoundException e) 
		{
			e.printStackTrace();
		}	
		
	}
	
	protected boolean onSavePrompt() {
        return true;
    }
	
	public void add(Field f)
	{
		_pane.add(f);
		_pane.invalidate();
		this.invalidate();
	}
	
	public VerticalFieldManager getContainer()
	{
		return this._pane;
	}
	
	protected void pushScreen( Screen toPush ) 
    {
        UiApplication.getUiApplication().pushScreen( toPush );
    }
	
	public void switchScreen(final ScreenTemplate nextScreen)
	{
		final UiApplication ui = UiApplication.getUiApplication();
		if(ui.getActiveScreen()  instanceof ScreenTemplate )
		{
			final ScreenTemplate currentScreen = (ScreenTemplate)ui.getActiveScreen();
			if (UiApplication.isEventDispatchThread()) {  
	            ui.popScreen(currentScreen);  
	            ui.pushScreen(nextScreen);  
	        } else {  
	            ui.invokeLater(new Runnable() {  
	                public void run() {  
	                    ui.popScreen(currentScreen);  
	                    ui.pushScreen(nextScreen);  
	                }  
	            });  
	        } 
		}
  
	}

	public void popScreen()
	{
		final UiApplication ui = UiApplication.getUiApplication();
		if(ui.getActiveScreen()  instanceof ScreenTemplate )
		{
			final ScreenTemplate currentScreen = (ScreenTemplate)ui.getActiveScreen();
			if (UiApplication.isEventDispatchThread()) {  
	            ui.popScreen(currentScreen);
	        } else {  
	            ui.invokeLater(new Runnable() {  
	                public void run() {  
	                    ui.popScreen(currentScreen);
	                }  
	            });  
	        } 
        } 
	}
	
	public void updateTitle(HorizontalFieldManager _h)
	{
		this.appIconField.deleteAll();
		this.appIconField.add(_h);
		//this.appIconField.invalidate();
		//this.invalidate();
	}
	public void checkSDCard()
	{
		boolean sdCardPresent = false;
        String root = null;
        Enumeration e = FileSystemRegistry.listRoots();
        while (e.hasMoreElements())
        {
            root = (String)e.nextElement();
            if(root.equalsIgnoreCase("sdcard/"))
            {
                sdCardPresent = true;
            }     
        }            
        if(!sdCardPresent)
        {
            UiApplication.getUiApplication().invokeLater(new Runnable()
            {
                public void run()
                {
                    Dialog.alert("This application requires an SD card to be present. Exiting application...");
                    System.exit(0);            
                } 
            });        
        }
	}
}
